package org.example.service;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.example.entity.Movie;
import org.example.entity.MovieType;
import org.w3c.dom.NodeList;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class CinemaService implements ICinemaService{

    @Override
    public void readXmlToMap() throws IOException {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new FileInputStream("movies.xml"));
            MOVIE_MAP.clear();
            List<Element> movieElements = document.getRootElement().elements("movie");
            for (Element movieElement : movieElements) {
                String id = movieElement.attributeValue("id");
                String name = movieElement.elementText("name");
                String direction = movieElement.elementText("direction");
                String actor = movieElement.elementText("actor");
                String type = movieElement.elementText("type");
                String price = movieElement.elementText("price");
                String playTime = movieElement.elementText("playTime");

                Movie movie = new Movie();
                movie.setId(Integer.parseInt( id));
                movie.setName(name);
                movie.setActor(actor);
                movie.setDirection(direction);
                movie.setType(MovieType.valueOf(type));
                movie.setPrice(Integer.parseInt(price));
                movie.setPlayTime(playTime);
                MOVIE_MAP.put(id, movie);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void showMovies() throws IOException {
        readXmlToMap();
        if (MOVIE_MAP.isEmpty()) {
            System.out.println("暂无电影信息");
            return;
        }

        System.out.println("\n========== 电影列表 ==========");
        int index = 1;
        for (Map.Entry<String, Movie> entry : MOVIE_MAP.entrySet()) {
            Movie movie = entry.getValue();
            System.out.println(movie);
            index++;
        }
        System.out.println("============================");
    }

    @Override
    public Movie getMovieByName(String name,String playTime) {
        try {
            readXmlToMap();
            for (Map.Entry<String, Movie> entry : MOVIE_MAP.entrySet()) {
                Movie movie = entry.getValue();
                if (movie.getName().equals(name) && movie.getPlayTime().equals(playTime)) {
                    return movie;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
